﻿using Microsoft.CSharp;
using NCalc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleNCalcu
{
    internal class Program2
    {      
        public static Dictionary<string, Dictionary<string, int>> finalResult = new Dictionary<string, Dictionary<string, int>>();
     
        public static Dictionary<string, int> toAdjustLevel = new Dictionary<string,int>();

        public  Dictionary<string, Result> final_result = new Dictionary<string, Result>();

        public static  List<string> model_codes = new List<string>();

        public static   Dictionary<string, CRule> neededRule = new Dictionary<string, CRule>();

        public static Dictionary<string, double> parametersResult = new Dictionary<string, double>();

        static void Main333(string[] args)
        {

            double score_f = Math.Round(82.5, MidpointRounding.AwayFromZero);

            Console.WriteLine(score_f.ToString());

     

            decimal score_f2 = (decimal)Math.Round(82.7, 0);

            Console.WriteLine(score_f2.ToString());



            string str1 = @"{""effortLevel"": {""standard"": ""50|80"", ""result"": ""1|2|3"", ""formula"": ""(thinking*1+thinkingActivity*1+lowFlow*1+singleMindedness*1+lfn*0.15)*100/16+max(0,(thinking-5)*10)+max(0,(lowFlow-5)*10)+max(0,(singleMindedness-5)*10)""}, ""focusOnInvestment"": {""standard"": ""50|80"", ""result"": ""1|2|3"", ""formula"": ""(lowFlow*2.1+singleMindedness*2.3+midFlow*5+highFlow*8)*100/8+max(0,(singleMindedness-5)*10)""}, ""enterprising"": {""standard"": ""50|80"", ""result"": ""1|2|3"", ""formula"": ""(impatient*3.5+worryTrait*5+crisisSense*0.8+thinkingActivity*0.8)*100/10+max(0,(impatient-5)*10)+max(0,(worryTrait-5)*10)""}, ""emotionManager"": {""standard"": ""30|60"", ""result"": ""1|2|3"", ""formula"": ""100-(emotionalActivity*0.8+emotionalStress*1+anxietyTrait*1+delicateSensitive*1+midMoodWave*0.8+highMoodWave*0.8+innerHelplessness*1+innerResistance*1)*100/6+max(0,(emotionalStress-5)*10)+max(0,(anxietyTrait-5)*10)+max(0,(innerHelplessness-5)*5)+max(0,(innerResistance-5)*8)""}, ""easyObedient"": {""standard"": ""30|60"", ""result"": ""1|2|3"", ""formula"": ""100-(worry*1+worryTrait*1+delicateSensitive*1+midMoodWave*0.8+highMoodWave*0.8+innerHelplessness*1+innerResistance*1)*100/6+max(0,(worry-5)*20)+max(0,(worryTrait-5)*10)+max(0,(delicateSensitive-5)*10)""}, ""activeMind"": {""standard"": ""50|80"", ""result"": ""1|2|3"", ""formula"": ""(thinkingActivity*0.5+thinking*1.4+lowFlow*1.3+singleMindedness*1.8+mentalStress*4)*100/5+max(0,(thinking-5)*5)+max(0,(lowFlow-5)*8)+max(0,(singleMindedness-5)*10)+max(0,(mentalStress-5)*10)""}, ""fatigueStatus"": {""standard"": ""17|40|85|95"", ""result"": ""1|2|3|4|5"", ""formula"": ""(mentalFatigue*6+visualFatigue*6+lowDepress*6+midDepress*8+highDepress*10-lfn*0.1)*100/28+max(0,(mentalFatigue-5)*10)+max(0,(lowDepress-5)*10)+max(0,(midDepress-5)*10)+max(0,(highDepress-5)*10)""}, ""energyStatus"": {""standard"": ""50|80"", ""result"": ""1|2|3"", ""formula"": ""(lfn*0.2-mentalFatigue*2.5-visualFatigue*1+thinkingActivity*1.8+crisisSense*1.8+lowAnxiety*0.8+midAnxiety*1+ highAnxiety*1-lowDepress*1.2-midDepress*1.2-highDepress*1.5)*100/30 + max(0,(thinkingActivity-5)*3)+max(0,(crisisSense-5)*5)+max(0,(highAnxiety-5)*5) - max(0,(lowDepress-5)*10)""}, ""model_codes"": [""effortLevel"", ""focusOnInvestment"", ""enterprising"", ""emotionManager"", ""easyObedient"", ""activeMind"", ""fatigueStatus"", ""energyStatus""]}";
            string str4 = "{\"effortLevel\": {\"standard\": \"50|80\", \"result\": \"1|2|3\", \"formula\": \"(thinking*1+thinkingActivity*1+lowFlow*1+singleMindedness*1+lfn*0.15)*100/16+max(0,(thinking-5)*10)+max(0,(lowFlow-5)*10)+max(0,(singleMindedness-5)*10)\"}, \"focusOnInvestment\": {\"standard\": \"50|80\", \"result\": \"1|2|3\", \"formula\": \"(lowFlow*2.1+singleMindedness*2.3+midFlow*5+highFlow*8)*100/8+max(0,(singleMindedness-5)*10)\"}, \"enterprising\": {\"standard\": \"50|80\", \"result\": \"1|2|3\", \"formula\": \"(impatient*3.5+worryTrait*5+crisisSense*0.8+thinkingActivity*0.8)*100/10+max(0,(impatient-5)*10)+max(0,(worryTrait-5)*10)\"}, \"emotionManager\": {\"standard\": \"30|60\", \"result\": \"1|2|3\", \"formula\": \"100-(emotionalActivity*0.8+emotionalStress*1+anxietyTrait*1+delicateSensitive*1+midMoodWave*0.8+highMoodWave*0.8+innerHelplessness*1+innerResistance*1)*100/6+max(0,(emotionalStress-5)*10)+max(0,(anxietyTrait-5)*10)+max(0,(innerHelplessness-5)*5)+max(0,(innerResistance-5)*8)\"}, \"easyObedient\": {\"standard\": \"30|60\", \"result\": \"1|2|3\", \"formula\": \"100-(worry*1+worryTrait*1+delicateSensitive*1+midMoodWave*0.8+highMoodWave*0.8+innerHelplessness*1+innerResistance*1)*100/6+max(0,(worry-5)*20)+max(0,(worryTrait-5)*10)+max(0,(delicateSensitive-5)*10)\"}, \"activeMind\": {\"standard\": \"50|80\", \"result\": \"1|2|3\", \"formula\": \"(thinkingActivity*0.5+thinking*1.4+lowFlow*1.3+singleMindedness*1.8+mentalStress*4)*100/5+max(0,(thinking-5)*5)+max(0,(lowFlow-5)*8)+max(0,(singleMindedness-5)*10)+max(0,(mentalStress-5)*10)\"}, \"fatigueStatus\": {\"standard\": \"17|40|85|95\", \"result\": \"1|2|3|4|5\", \"formula\": \"(mentalFatigue*6+visualFatigue*6+lowDepress*6+midDepress*8+highDepress*10-lfn*0.1)*100/28+max(0,(mentalFatigue-5)*10)+max(0,(lowDepress-5)*10)+max(0,(midDepress-5)*10)+max(0,(highDepress-5)*10)\"}, \"energyStatus\": {\"standard\": \"50|80\", \"result\": \"1|2|3\", \"formula\": \"(lfn*0.2-mentalFatigue*2.5-visualFatigue*1+thinkingActivity*1.8+crisisSense*1.8+lowAnxiety*0.8+midAnxiety*1+ highAnxiety*1-lowDepress*1.2-midDepress*1.2-highDepress*1.5)*100/30 + max(0,(thinkingActivity-5)*3)+max(0,(crisisSense-5)*5)+max(0,(highAnxiety-5)*5) - max(0,(lowDepress-5)*10)\"}}";
            string str2 = @"{ ""lfnSet"": [60,60,60,60,60,60],""thinkingActivitySet"": [1,1,-1,-1,-1,-1],""thinkingSet"": [1,-1,-1,-1,-1,-1],""singleMindednessSet"": [1,1,-1,-1,1,-1],""highFlowSet"": [1,-1,-1,-1,-1,-1],""midFlowSet"": [1,-1,-1,-1,-1,-1],""lowFlowSet"": [1,-1,-1,-1,-1,-1],""highAnxietySet"": [1,1,-1,-1,1,-1],""midAnxietySet"": [1,1,-1,-1,1,-1],""lowAnxietySet"": [1,1,-1,-1,1,-1],""highDepressSet"": [1,1,-1,-1,1,-1],""midDepressSet"": [1,1,-1,-1,1,-1],""lowDepressSet"": [1,1,-1,-1,1,-1],""highMoodWaveSet"": [-1,-1,-1,-1,-1,-1],""midMoodWaveSet"": [-1,-1,-1,-1,-1,-1],""innerResistanceSet"": [-1,-1,-1,-1,-1,-1],""innerHelplessnessSet"": [-1,-1,-1,-1,-1,-1],""emotionalActivitySet"": [1,-1,-1,-1,-1,-1],""emotionalStressSet"": [-1,-1,1,-1,-1,-1],""mentalFatigueSet"": [-1,1,1,-1,1,-1],""visualFatigueSet"": [-1,1,1,-1,1,-1],""mentalStressSet"": [-1,-1,-1,-1,-1,-1],""anxietyTraitSet"": [-1,-1,-1,1,-1,-1],""delicateSensitiveSet"": [-1,-1,-1,-1,-1,-1],""impatientSet"": [-1,-1,-1,-1,-1,-1],""crisisSenseSet"": [-1,-1,-1,-1,-1,-1],""worrySet"": [1,1,0,1,0,1],""worryTraitSet"": [-1,-1,-1,-1,-1,-1],""drowsinessLevel"":[0],""sleepStage"":[1]}";
            string str3 = @"{""drowsinessLevel"":0,""sleepStage"":1}";

            string strConfig1 = @"{""analysisModels"":[""energyStatus"",""effortLevel"",""fatigueStatus"",""emotionManager"",""easyObedient"",""activeMind"",""focusOnInvestment"",""enterprising""],""statusCodes"":[""positive"",""serious"",""normal"",""common"",""relax"",""rest"",""-1""],""eventPointsUp"":[""difficult"",""detail"",""thinking"",""focus"",""downcast"",""nervous""],""eventPointsDown"":[""fatigue"",""helpless"",""worry"",""emotion"",""excite""]}";

            string str7 = @"{""adultEpilepsySet"":[0,0,0,0,0,0],""anginaSet"":[-2,-99,-2,-2,-2,-2],""highAnxietySet"":[-2,-2,-2,-2,-2,1],""midAnxietySet"":[-2,-2,-2,-2,-2,-1],""lowAnxietySet"":[-2,-2,-2,-2,-2,-1],""anxietyTraitSet"":[-2,-2,-2,-2,-2,-2],""bloodOxygenSet"":[0,0,0,0,0,0],""singleMindednessSet"":[-2,-2,-2,-2,-2,-2],""childrenEpilepsySet"":[0,0,0,0,0,0],""chronicPainSet"":[-2,-2,-2,-2,-2,-2],""mentalStressSet"":[-2,-2,-2,-2,-2,-2],""thinkingActivitySet"":[-2,-2,-2,-2,-2,-2],""coronaryAtherosclerosisSet"":[-2,-2,-2,-2,-2,-2],""coronaryDiseaseSet"":[-2,-2,-2,-2,-2,-2],""highCrossOutSet"":[-2,-2,-2,-2,-2,-2],""lowCrossOutSet"":[-2,-2,-2,-2,-2,-2],""highDepressSet"":[-2,-2,-2,-2,-2,-2],""midDepressSet"":[-2,-2,-2,-2,-2,-2],""lowDepressSet"":[-2,-2,-2,-2,-2,-2],""diabetesType1Set"":[-2,-2,-2,-2,-2,-2],""diabetesType2Set"":[-2,-2,-2,-2,-2,-2],""drunkSet"":[-2,-2,-2,-2,-2,-2],""drunk2Set"":[-2,-2,-2,-2,-2,-2],""emotionalStressSet"":[-2,-2,-2,-2,-2,-2],""emotionalActivitySet"":[-2,-2,-2,-2,-2,-2],""erectileDysfunctionSet"":[0,0,0,0,0,0],""essentialHypertensionSet"":[-2,-2,-2,-2,-2,-2],""midFeverSet"":[-2,-2,-2,-2,-2,-2],""lowFeverSet"":[-2,-2,-2,-2,-2,-2],""highFlowSet"":[-2,-2,-2,-2,-2,-2],""midFlowSet"":[-2,-2,-2,-2,-2,-2],""lowFlowSet"":[-2,-2,-2,-2,-2,-2],""heartFailureSet"":[-2,-2,-2,-2,-2,-2],""heartRateTenAvgSet"":[78,83,83,82,85,84],""highHeroinAddictionSet"":[-1,-1,-1,-1,-1,-1],""lowHeroinAddictionSet"":[-1,-1,-1,-1,-1,-1],""thinkingSet"":[-1,-1,-1,-1,-1,-1],""highMoodWaveSet"":[-1,-1,-1,-1,-1,-1],""midMoodWaveSet"":[-1,-1,-1,-1,-1,-1],""lfnSet"":[31,30,38,55,64,77],""lfnAvgSet"":[35,33,35,39,43,48],""meanRateSet"":[78,77,77,80,81,83],""mentalFatigueSet"":[-2,-2,-2,-2,-2,-1],""delicateSensitiveSet"":[-2,-2,-2,-2,-2,-2],""nocturnalHypoglycemiaSet"":[0,0,0,0,0,0],""onLineGameAddictionSet"":[-2,-2,-2,-2,-2,-2],""ruminationSet"":[-2,-2,-2,-2,-2,-2],""highShiYingLevelSet"":[-1,-1,-1,-1,-1,-1],""midShiYingLevelSet"":[-1,-1,-1,-1,-1,-1],""lowShiYingLevelSet"":[-1,-1,-1,-1,-1,-1],""stimPainSet"":[-2,-2,-2,-2,1,1],""strokeSet"":[-2,-2,-2,-2,-2,-2],""suddenCardiacDeathSet"":[-2,-2,-2,-2,-2,-2],""impatientSet"":[-2,-2,-2,-2,-2,-2],""crisisSenseSet"":[-2,-2,-2,-2,-2,-2],""visualFatigueSet"":[-2,-2,-1,-1,-1,-1],""worrySet"":[-2,-2,-2,-2,-2,-2],""worryTraitSet"":[-2,-2,-2,-2,-2,-2],""innerResistanceSet"":[-1,-1,-1,-1,-1,-1],""innerHelplessnessSet"":[-1,-1,-1,-1,-1,-1],""sleepStage"":[4],""drowsinessLevel"":[0]}";
            //Mono.CSharp 调用时

            // str1 = str1.Replace("\"", "\\\"");   //将单引号(") 变成(\")
            //  str2 = str2.Replace("\"", "\\\"");


            string str8 = @"{""effortLevel"": {""standard"": ""50|80"", ""result"": ""1|2|3"", ""formula"": ""(thinking*1+thinkingActivity*1+lowFlow*1+singleMindedness*1+lfn*0.15)*100/16+max(0,(thinking-5)*10)+max(0,(lowFlow-5)*10)+max(0,(singleMindedness-5)*10)""}, ""focusOnInvestment"": {""standard"": ""50|80"", ""result"": ""1|2|3"", ""formula"": ""(lowFlow*2.1+singleMindedness*2.3+midFlow*5+highFlow*8)*100/8+max(0,(singleMindedness-5)*10)""}, ""enterprising"": {""standard"": ""50|80"", ""result"": ""1|2|3"", ""formula"": ""(impatient*3.5+worryTrait*5+crisisSense*0.8+thinkingActivity*0.8)*100/10+max(0,(impatient-5)*10)+max(0,(worryTrait-5)*10)""}, ""emotionManager"": {""standard"": ""30|60"", ""result"": ""1|2|3"", ""formula"": ""100-(emotionalActivity*0.8+emotionalStress*1+anxietyTrait*1+delicateSensitive*1+midMoodWave*0.8+highMoodWave*0.8+innerHelplessness*1+innerResistance*1)*100/6+max(0,(emotionalStress-5)*10)+max(0,(anxietyTrait-5)*10)+max(0,(innerHelplessness-5)*5)+max(0,(innerResistance-5)*8)""}, ""easyObedient"": {""standard"": ""30|60"", ""result"": ""1|2|3"", ""formula"": ""100-(worry*1+worryTrait*1+delicateSensitive*1+midMoodWave*0.8+highMoodWave*0.8+innerHelplessness*1+innerResistance*1)*100/6+max(0,(worry-5)*20)+max(0,(worryTrait-5)*10)+max(0,(delicateSensitive-5)*10)""}, ""activeMind"": {""standard"": ""50|80"", ""result"": ""1|2|3"", ""formula"": ""(thinkingActivity*0.5+thinking*1.4+lowFlow*1.3+singleMindedness*1.8+mentalStress*4)*100/5+max(0,(thinking-5)*5)+max(0,(lowFlow-5)*8)+max(0,(singleMindedness-5)*10)+max(0,(mentalStress-5)*10)""}, ""fatigueStatus"": {""standard"": ""17|40|85|95"", ""result"": ""1|2|3|4|5"", ""formula"": ""(mentalFatigue*6+visualFatigue*6+lowDepress*6+midDepress*8+highDepress*10-lfn*0.1)*100/28+max(0,(mentalFatigue-5)*10)+max(0,(lowDepress-5)*10)+max(0,(midDepress-5)*10)+max(0,(highDepress-5)*10)""}, ""energyStatus"": {""standard"": ""50|80"", ""result"": ""1|2|3"", ""formula"": ""(lfn*0.2-mentalFatigue*2.5-visualFatigue*1+thinkingActivity*1.8+crisisSense*1.8+lowAnxiety*0.8+midAnxiety*1+ highAnxiety*1-lowDepress*1.2-midDepress*1.2-highDepress*1.5)*100/30 + max(0,(thinkingActivity-5)*3)+max(0,(crisisSense-5)*5)+max(0,(highAnxiety-5)*5) - max(0,(lowDepress-5)*10)""}, ""model_codes"": [""effortLevel"", ""focusOnInvestment"", ""enterprising"", ""emotionManager"", ""easyObedient"", ""activeMind"", ""fatigueStatus"", ""energyStatus""]}";

            bool x = ConfigureParas(strConfig1, str4);


          string lastResult=  OneMinuteAnalysis(str7);
            Console.WriteLine(lastResult);
            Console.ReadKey();
        }



        public static bool ConfigureParas(string neededIndexes, string setting_data)
        {
            Dictionary<string,List<string>> neededData = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(neededIndexes);

            model_codes = neededData["analysisModels"];

            Dictionary<string, object> settingData = JsonConvert.DeserializeObject<Dictionary<string, object>>(setting_data);

            if (neededRule!=null)
            {
                neededRule.Clear();
                toAdjustLevel.Clear();
            }           


            foreach (string item in model_codes)
            {
                // neededRule.Add(item, settingData[item]);
                CRule a = JsonConvert.DeserializeObject<CRule>(settingData[item].ToString());
                settingData[item] = a;
                neededRule.Add(item, a);   

               // final_result.Add(item, new Result() { });
                toAdjustLevel.Add(item, 0);
            }

            return true;

        }


        public static bool correct_condition(double drowsinessLevel, double sleepStage)
        {
            if (drowsinessLevel > 0 || sleepStage == 1 || sleepStage == 2 || sleepStage == 3 || sleepStage == 0)
            {
                return true;
            }
            return false;
        }     


        public static string OneMinuteAnalysis(string value_json)
        {         

            parametersResult = new Dictionary<string, double>(); 

            // 解析  一分钟对应的数据  
            //  Dictionary<string, List<int>> settingDataValue = JsonConvert.DeserializeObject<Dictionary<string, List<int>>(value_json);

            parametersResult.Clear();

            Dictionary<string, List<int>> settingDataValue = JsonConvert.DeserializeObject<Dictionary<string, List<int>>>(value_json);
            string result = "{\n";
            foreach (var kvp in settingDataValue)
            {
                result += $"  \"{kvp.Key}\" : [{string.Join(", ", kvp.Value)}],\n";
            }
            result = result.TrimEnd(',', '\n') + "\n}";
            
            if (result.Contains("-99"))
            {
                foreach (var item in model_codes)
                {
                    finalResult[item] = new Dictionary<string, int>()
                      {
                    {"score", -1},
                    {"level",-1}
                       };
                  }

              string offlineData=  JsonConvert.SerializeObject(finalResult);
              return offlineData;
                
            }
            foreach (var item in settingDataValue.Keys)
            {
              
                if (item == "lfnSet")
                {
                    var var1 = settingDataValue[item].Sum(x => x);
                    var var2 = settingDataValue[item].Count(x => x == -1);
                    var var3 = settingDataValue[item].Count;
                    var var4 = (var1 + var2) / (var3 - var2);
                    parametersResult.Add("lfn", var4);
                }
                else if (item == "drowsinessLevel" || item == "sleepStage")
                {
                    parametersResult.Add(item, settingDataValue[item][settingDataValue[item].Count - 1]);
                }
                else
                {
                    string var5 = item.Replace("Set", "");
                    parametersResult.Add(var5, settingDataValue[item].Count(x => x == 1));
                }
                // parametersResult.Add(item,)

            }

            foreach (string itemX in neededRule.Keys)
            {
                CalculateCfactor(itemX, neededRule);
            }         

            string json = JsonConvert.SerializeObject(finalResult);          

            return json;
        }
        public static List<string> FindItemsWithChar(List<string> lst, string str)
        {
            List<string> result = new List<string>();
            foreach (string item in lst)
            {
                if (item.Contains(str))
                {
                    result.Add(item);
                }
            }
            return result;
        }


        public static double EvaluateFormula(string someIndex, string formula)
        {
            // Evaluate the formula and return the score

            Expression e = new Expression(formula, EvaluateOptions.IgnoreCase);

            foreach (string item in parametersResult.Keys)
            {
                e.Parameters[item] = parametersResult[item];
            }

            var result = e.Evaluate();

            return (double)result;
        }


        public static int AdjustLevel( string formula)
        {
            // Evaluate the formula and return the score

            Expression e = new Expression(formula, EvaluateOptions.IgnoreCase);

            foreach (string item in toAdjustLevel.Keys)
            {
                e.Parameters[item] = toAdjustLevel[item];
            }

            var result = e.Evaluate();


            return (int )result;
        }

        public static void CalculateCfactor(string variable, Dictionary<string, CRule> modelSettingData)
        {
            List<string> correct_result = new List<string>()
                 {
                "Max(energyStatus - 1, 1)",
                "Max(effortLevel - 1, 1)",
                "Max(focusOnInvestment - 1, 1)",
                "Max(enterprising - 1, 1)",
                "Min(easyObedient + 1, 3)",
                "Min(emotionManager + 1, 3)",
                "Min(fatigueStatus + 2, 5)"
                 };
            double score = EvaluateFormula(variable, modelSettingData[variable].formula);

            score = ModifyScore(score);

            string[] standard = modelSettingData[variable].standard.Split('|');
            string[] result = modelSettingData[variable].result.Split('|');
            int resultLevel = 0;
            for (int i = 0; i < standard.Length; i++)
            {
                if (score <= double.Parse(standard[i]))
                {
                    resultLevel = int.Parse(result[i]);
                    break;
                }
            }
            if (resultLevel == 0)
            {
                resultLevel = int.Parse(result[result.Length - 1]);
            }

            toAdjustLevel[variable] = resultLevel;
            //

            if (correct_condition(parametersResult["drowsinessLevel"], parametersResult["sleepStage"]))
            {
                List<string> result2 = FindItemsWithChar(correct_result, variable);
                if (result2.Count > 0)             
                {
                    resultLevel = AdjustLevel(result2[0]);
                }
            }

            finalResult[variable] = new Dictionary<string, int>()
              {
            {"score", (int)score},
            {"level", resultLevel}
               };

        }

        public static double ModifyScore(double score)
        {
            if (score < 0)
            {
                score = 20 - Math.Log(Math.Abs(score) + 1);
            }
            else if (score >= 99)
            {
                score = 90 + Math.Log(score - 99 + 1);
            }
            double score_f =Math.Round(score, MidpointRounding.AwayFromZero);
            return score_f;
        }
    }
    public class CRule
    {
        public string standard { get; set; }
        public string result { get; set; }
        public string formula { get; set; }
    }
    public class Result
    {
        public int score { get; set; }
        public int level { get; set; }
    }



    //public class AnalysisEventPoint
    //{
    //    /// <summary>
    //    /// 事件码
    //    /// </summary>
    //    public string eventCode;

    //    /// <summary>
    //    /// 事件发生时间索引
    //    /// </summary>
    //    public int index;
    //}
    //public class EventPoint
    //{
    //    public List<Dictionary<string, List<Dictionary<string, string>>>> eventPoint { get; set; }
    //}

    //public class EventPoints
    //{
    //  // public Dictionary<string, List<AnalysisEventPoint>> eventPoints { get; set; }

    //    public Dictionary<string, List<AnalysisEventPoint>> eventPoint { get; set; }



    //}

    //public class ThreeResults
    //{
    //    public string status { get; set; }
    //    public List<EventPoints>  eventPoints { get; set; }
    //}

    public class EventDetail
    {
        public string eventCode { get; set; }
        public int index { get; set; }
    }

    public class EventPoint
    {
        public List<EventDetail> up { get; set; }
        public List<EventDetail> down { get; set; }
    }

    public class StatusEvent
    {
        public string status { get; set; }
        public List<EventPoint> eventPoint { get; set; }

    }

   public class StatusEventNew
    {

        /// <summary>
        /// 状态
        /// </summary>
        public string status;
        /// <summary>
        /// 事件点集合
        /// </summary>
        public Dictionary<string, List<Dictionary<string, List<Dictionary<string, string>>>>> eventPoint;

       
    }


    public class Program
    {

        //一分钟计算结果   

        //   key= 模型的二级指标    value=dict<string,string> score  yu level   

        //    {'effortLevel': {'score': 91, 'level': 2},
        //    'focusOnInvestment': {'score': 95, 'level': 2},
        //    'enterprising': {'score': 16, 'level': 1},
        //    'emotionManager': {'score': 53, 'level': 3},
        //    'easyObedient': {'score': 33, 'level': 3},
        //    'activeMind': {'score': 94, 'level': 3},
        //    'fatigueStatus': {'score': 96, 'level': 5},
        //    'energyStatus': {'score': 6, 'level': 1}}




        //"statusCodes"":[""positive"",""serious"",""normal"",""common"",""relax"",""rest"",""-1""]

        // 需要的状态编码   内部含有  事件码：上下 
        // 
        //三分钟的计算结果   

        //  {'status': 'normal', 'eventPoint': [{'up': [{'eventCode': 'difficult', 'index': 2},
        //                                          {'eventCode': 'focus', 'index': 2},
        //         {'eventCode': 'thinking', 'index': 2}]},
        //        {
        //'down': [{ 'eventCode': 'helpless', 'index': 2},
        //         { 'eventCode': 'worry', 'index': 2},
        //         { 'eventCode': 'emotion', 'index': 2},
        //         { 'eventCode': 'excite', 'index': 2}]}]},




        // "analysisModels":[""energyStatus"",""effortLevel"",""fatigueStatus"",""emotionManager"",""easyObedient"",""activeMind"",""focusOnInvestment"",""enterprising""],

        //模型的二级指标   要计算的指标列表  

        public static Random random = new Random();

        //状态列表
        public static List<string> status = new List<string>();
        public static List<string> up_event = new List<string>();
        public static List<string> down_event = new List<string>();

        //"statusCodes":["positive","serious","normal","common","relax","rest"],"statusScore":[6,5,4,3,2,1],
        public static List<string> status_codes = new List<string>();
        public static List<int> status_score = new List<int>();
        public static Dictionary<string, string> variables = new Dictionary<string, string>();
        public static List<string> randoms = new List<string>();
        public static Dictionary<string, string> none_opts = new Dictionary<string, string>();
        public static string offline_des = "期间出现较长时间断线，评估结果仅供参考。";


        public static Dictionary<string, Dictionary<string, string>> setting_data_global = new Dictionary<string, Dictionary<string, string>>();

    
        
        public static string GetRandom(string result)
        {
            List<string> list_result = result.Split(',').ToList();
            if (randoms.Count > 0)
            {
                var var = list_result.Except(randoms).ToList();
                if (var.Count == 0)
                {
                    var value = list_result[random.Next(list_result.Count)];
                    return value;
                }
                else
                {
                    var value = var[random.Next(var.Count)];
                    return value;
                }
            }
            else
            {
                var value = list_result[random.Next(list_result.Count)];
                return value;
            }
        }

        public static void GetTrend(string variable, float slope, Dictionary<string, Dictionary<string, string>> setting_data)
        {
            var trend = setting_data[variable + "_trend"];

            var standard = trend["standard"].Split('|').ToList();
            var result = trend["result"].Split('|').ToList();
            var final_result = "";
            for (int i = 0; i < standard.Count; i++)
            {
                if (slope <= float.Parse(standard[i]))
                {
                    final_result = result[i];
                    break;
                }
            }
            if (final_result == "")
            {
                final_result = result[result.Count - 1];
            }

            variables[variable + "_trend"] = GetRandom(final_result);
        }

        public static string GetFrequence(float frequence, Dictionary<string, Dictionary<string, string>> setting_data)
        {
            var trend = setting_data["frequence"];
            var standard = trend["standard"].Split('|').ToList();
            var result = trend["result"].Split('|').ToList();
            var final_result = "";
            for (int i = 0; i < standard.Count; i++)
            {
                if (frequence <= float.Parse(standard[i]))
                {
                    final_result = result[i];
                    break;
                }
            }
            if (final_result == "")
            {
                final_result = result[result.Count - 1];
            }

            return GetRandom(final_result);
        }

        public static void CalculateStatus(ref Dictionary<string, Dictionary<string, string>> setting_data)
        {

            var status_dict = status_codes.Zip(status_score, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v);

            var total_score = status.Sum(s => status_dict[s]);

            var average_score = Math.Round((float)total_score / status.Count);

            var status_slope = (status_dict[status.Last()] - status_dict[status.First()]) / status.Count;

            var final_status = status_dict.FirstOrDefault(x => x.Value == average_score).Key;
            variables["status"] = final_status;
            GetTrend("status", status_slope, setting_data);

        }

        public static void CalculateKeyEvent(Dictionary<string, Dictionary<string, string>> setting_data)
        {

            var counter = up_event.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());

            var most_common_three = counter.OrderByDescending(x => x.Value).Take(3).ToList();
            if (most_common_three.Count == 0)
            {
                none_opts["key_event"] = "1";
            }

            var keys = new List<string>();
            var total_count = status.Count;
            foreach (var item in most_common_three)
            {
                var pctg = (float)item.Value / total_count * 100;
                keys.Add(GetFrequence(pctg, setting_data) + "的{" + item.Key + "}");
            }
            var result = string.Join("、", keys);
            variables["keyevent"] = result;

        }

        public static void CalculateExtEvent(Dictionary<string, Dictionary<string, string>> setting_data)
        {

            var counter = down_event.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());

            var most_common_three = counter.OrderByDescending(x => x.Value).Take(3).ToList();
            if (most_common_three.Count == 0)
            {
                none_opts["ext_event"] = "1";
            }

            var keys = new List<string>();
            var total_count = status.Count;
            foreach (var item in most_common_three)
            {
                var pctg = (float)item.Value / total_count * 100;
                keys.Add(GetFrequence(pctg, setting_data) + "的{" + item.Key + "}");
            }
            var result = string.Join("、", keys);
            variables["extevent"] = result;

        }





        public static string ParseStatusAndEvent(string value_json)
        {
            var count = 0;
            //List<Dictionary<string, List<ThreeResults>>> eventPointX5 = new List<Dictionary<string, List<ThreeResults>>>();

            List<StatusEvent> threeResults = new List<StatusEvent>();
            threeResults = JsonConvert.DeserializeObject<List<StatusEvent>>(value_json);
            if (threeResults.Count != 0)
            {
                foreach (var item in threeResults)
                {
                    if (item.status != "-1")
                    {
                        status.Add(item.status);

                        foreach (var eventPoint in item.eventPoint)
                        {
                            if (eventPoint.up != null)
                            {
                                foreach (var itemX3 in eventPoint.up)
                                {
                                    up_event.Add(itemX3.eventCode);
                                }
                            }
                            else if (eventPoint.down != null)
                            {
                                foreach (var itemX3 in eventPoint.down)
                                {
                                    down_event.Add(itemX3.eventCode);
                                }
                            }                            

                        }
                        count += 1;
                    }

                }
            }



            var percetage = count * 100 / threeResults.Count;
            if (percetage < 10)
            {
                return "long_offline";
            }
            else if (percetage < 50)
            {
                return "part_offline";
            }
            else
            {
                return "";
            }
        }

        public static void ParseSetting()
        {
            //Dictionary<string, Dictionary<string, string>> setting_data

            

            string str1 = "[\"positive\",\"serious\",\"normal\",\"common\",\"relax\",\"rest\"]";
            if (str1 != null)
            {
                status_codes = JsonConvert.DeserializeObject<List<string>>(str1);
            }

            

           // status_codes=
            
            string str2 = "[6,5,4,3,2,1]";
            status_score = JsonConvert.DeserializeObject<List<int>>(str2);
            //status_codes = setting_data["status_codes"]["result"].Split('|').ToList();

            // ["positive","serious","normal","common","relax","rest"]

            //状态 分数 啥意思   根据二级指标得到的分数   15分钟  5个三分钟   15个一分钟的Score

            // "statusCodes":["positive","serious","normal","common","relax","rest"],"statusScore":[6,5,4,3,2,1],

            //"qualitativeCode":"statusQualitative",
            //"quantitativeCode":"statusQuantitative",
            // "eventCode":"eventPoints",   

            //"statusCodes":["positive","serious","normal","common","relax","rest"],
            //"statusScore":[6,5,4,3,2,1],

            // "periodCode":"periodStatus",  // 15分钟
            // "totalCode":"totalStatus",    // 结束总评 





            //status_score = setting_data["status_score"]["result"].Split('|').Select(int.Parse).ToList();

            // [6,5,4,3,2,1]


            //foreach (var item in setting_data)
            //{
            //    if (item.Key != "status_codes" && item.Key != "model_code" && item.Key != "status_score" && item.Value["standard"] == "None")
            //    {
            //        variables[item.Key] = GetRandom(item.Value["result"]);
            //    }
            //}




            // variables["periodCode"] =;
            // variables["totalCode"] =;
            // variables["eventPoints"] =;

        }

        public static void AnalysisModel(Dictionary<string, Dictionary<string, string>> setting_data, string value_json)
        {
            try
            {
                var offline_status = ParseStatusAndEvent(value_json);
                if (offline_status == "long_offline")
                {
                    var result333_json = new Dictionary<string, string> { { "period_des", "断线时间较长，不做评价" } };
                    Console.WriteLine(result333_json);
                    return;
                }
                setting_data = setting_data.ToDictionary(x => x.Key, x => x.Value.ToDictionary(y => y.Key, y => y.Value));
                ParseSetting(setting_data);
                CalculateStatus(setting_data);
                CalculateKeyEvent(setting_data);
                CalculateExtEvent(setting_data);

                var model_code = setting_data["model_code"]["result"];
                model_code = model_code.Substring(2, model_code.Length - 5).Replace("{frequence}", "");
                var final_result = model_code;
                foreach (var variable in variables)
                {
                    final_result = final_result.Replace("{" + variable.Key + "}", variable.Value);
                }
                final_result = final_result.Replace("{" + "key_event" + "}", variables["keyevent"]);
                final_result = final_result.Replace("{" + "ext_event" + "}", variables["extevent"]);
                if (none_opts.ContainsKey("key_event"))
                {
                    var start_index = final_result.IndexOf("其中");
                    var end_index = final_result.IndexOf("，", start_index);
                    final_result = final_result.Substring(0, start_index - 1) + final_result.Substring(end_index);
                }
                if (none_opts.ContainsKey("ext_event"))
                {
                    var start_index = final_result.IndexOf("并伴随");
                    final_result = final_result.Substring(0, start_index - 1) + final_result.Substring(start_index + 3);
                }
                if (offline_status == "part_offline")
                {
                    final_result = final_result + offline_des;
                }
                var result_json = new Dictionary<string, string> { { "period_des", final_result } };
                Console.WriteLine(result_json);
            }
            catch (Exception e)
            {
                Console.WriteLine("fail");
            }
        }

        public static void Main(string[] args)
        {
            var setting_data = new Dictionary<string, Dictionary<string, string>>();
            var value_json = @"[{'status': 'positive', 'eventPoint': [{'up': [{'eventCode': 'difficult', 'index': 2},
                                                             {'eventCode': 'focus', 'index': 2},
                                                             {'eventCode': 'thinking', 'index': 2}]},
                                                     {'down': [{'eventCode': 'helpless', 'index': 2},
                                                               {'eventCode': 'worry', 'index': 2},
                                                               {'eventCode': 'emotion', 'index': 2},
                                                               {'eventCode': 'excite', 'index': 2}]}]},
               {'status': 'serious', 'eventPoint': [{'up': [{'eventCode': 'difficult', 'index': 2},
                                                             {'eventCode': 'focus', 'index': 2},
                                                             {'eventCode': 'thinking', 'index': 2}]},
                                                     {'down': [{'eventCode': 'helpless', 'index': 2},
                                                               {'eventCode': 'worry', 'index': 2},
                                                               {'eventCode': 'emotion', 'index': 2},
                                                               {'eventCode': 'excite', 'index': 2}]}]},
               {'status': 'normal', 'eventPoint': [{'up': [{'eventCode': 'difficult', 'index': 2},
                                                             {'eventCode': 'focus', 'index': 2},
                                                             {'eventCode': 'thinking', 'index': 2}]},
                                                     {'down': [{'eventCode': 'helpless', 'index': 2},
                                                               {'eventCode': 'worry', 'index': 2},
                                                               {'eventCode': 'emotion', 'index': 2},
                                                               {'eventCode': 'excite', 'index': 2}]}]},
               {'status': 'normal', 'eventPoint': [{'up': [{'eventCode': 'difficult', 'index': 2},
                                                             {'eventCode': 'focus', 'index': 2},
                                                             {'eventCode': 'thinking', 'index': 2}]},
                                                     {'down': [{'eventCode': 'helpless', 'index': 2},
                                                               {'eventCode': 'worry', 'index': 2},
                                                               {'eventCode': 'emotion', 'index': 2},
                                                               {'eventCode': 'excite', 'index': 2}]}]},
               {'status': 'common', 'eventPoint': [{'up': [{'eventCode': 'difficult', 'index': 2},
                                                             {'eventCode': 'focus', 'index': 2},
                                                             {'eventCode': 'thinking', 'index': 2}]},
                                                     {'down': [{'eventCode': 'helpless', 'index': 2},
                                                               {'eventCode': 'worry', 'index': 2},
                                                               {'eventCode': 'emotion', 'index': 2},
                                                               {'eventCode': 'excite', 'index': 2}]}]}
               ]";

            string json_string = @"[ {'status': 'positive', 'eventPoint': [{'up': [{'eventCode': 'difficult', 'index': 2}, {'eventCode': 'focus', 'index': 2}, {'eventCode': 'thinking', 'index': 2}]}, {'down': [{'eventCode': 'helpless', 'index': 2}, {'eventCode': 'worry', 'index': 2}, {'eventCode': 'emotion', 'index': 2}, {'eventCode': 'excite', 'index': 2}]}]}, {'status': 'serious', 'eventPoint': [{'up': [{'eventCode': 'difficult', 'index': 2}, {'eventCode': 'focus', 'index': 2}, {'eventCode': 'thinking', 'index': 2}]}, {'down': [{'eventCode': 'helpless', 'index': 2}, {'eventCode': 'worry', 'index': 2}, {'eventCode': 'emotion', 'index': 2}, {'eventCode': 'excite', 'index': 2}]}]}, {'status': 'normal', 'eventPoint': [{'up': [{'eventCode': 'difficult', 'index': 2}, {'eventCode': 'focus', 'index': 2}, {'eventCode': 'thinking', 'index': 2}]}, {'down': [{'eventCode': 'helpless', 'index': 2}, {'eventCode': 'worry', 'index': 2}, {'eventCode': 'emotion', 'index': 2}, {'eventCode': 'excite', 'index': 2}]}]}, {'status': 'normal', 'eventPoint': [{'up': [{'eventCode': 'difficult', 'index': 2}, {'eventCode': 'focus', 'index': 2}, {'eventCode': 'thinking', 'index': 2}]}, {'down': [{'eventCode': 'helpless', 'index': 2}, {'eventCode': 'worry', 'index': 2}, {'eventCode': 'emotion', 'index': 2}, {'eventCode': 'excite', 'index': 2}]}]}, {'status': 'common', 'eventPoint': [{'up': [{'eventCode': 'difficult', 'index': 2}, {'eventCode': 'focus', 'index': 2}, {'eventCode': 'thinking', 'index': 2}]}, {'down': [{'eventCode': 'helpless', 'index': 2}, {'eventCode': 'worry', 'index': 2}, {'eventCode': 'emotion', 'index': 2}, {'eventCode': 'excite', 'index': 2}]}]} ]";


            //    AnalysisModel(setting_data, value_json);


            ParseStatusAndEvent(json_string);
            ParseSetting();
        }
    }











}
